package demo.proxy;


import java.lang.reflect.Field;

/**
 * @author : feixiang.li
 * @since : 2025-09-18 13:55
 */
public class Main {

    public static void main(String[] args) throws Exception {
        MyInterface myInterface = MyInterfaceFactory.createProxy(new MyHandlerImpl());
        myInterface.doSomething();
        myInterface.func1();
        myInterface.func2();
        System.out.println("-----------");
        MyInterface proxy = MyInterfaceFactory.createProxy(new LogHandler(myInterface));
        proxy.doSomething();
        proxy.func1();
        proxy.func2();
    }

    static class MyHandlerImpl implements MyHandler {
        public String getBody(String methodName) {

            StringBuilder sb = new StringBuilder();
            sb.append("     System.out.println(\"methodName:+ " + methodName + "\");\n");
            sb.append("System.out.println(System.currentTimeMillis());");
            return sb.toString();
        }
    }


    static class LogHandler implements MyHandler {

        MyInterface other;

        public LogHandler(MyInterface my) {
            this.other = my;
        }

        public void setProxy(MyInterface proxy) throws Exception {
            Class<? extends MyInterface> clazz = proxy.getClass();
            Field field = clazz.getDeclaredField("my");
            field.setAccessible(true);
            field.set(proxy, other);
        }

        public String getBody(String methodName) {

            String content = "          System.out.println(\"before\");\n" +
                    "            my." + methodName + "();\n" +
                    "            System.out.println(\"after\");";
            return content;
        }
    }
}
